<template>
  <div style="background-color: #f0f3fb; padding: 10px">
    <!-- 基本信息模块 -->
    <div style="background-color: #fff; border-radius: 5px; padding: 10px">
      <div style="display: flex">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
        <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">基础信息</div>
      </div>

      <!-- 活动名称输入框-->
      <div style="display: flex; align-items: center">
        <div style="width: 90px">活动名称:</div>
        <input v-model="spForm.name" class="input_class" placeholder="请填写活动名称" />
      </div>

      <!-- 商品说明输入框 -->
      <!-- <div style="display: flex; align-items: center">
        <div style="width: 90px">商品说明:</div>
        <textarea v-model="spForm.illustrate" class="textarea_class" placeholder="请写下商品的简介,便于用户了解商品"></textarea>
      </div> -->
      <Rboy-editor ref="RboyEditor" @uploadFile="uploadFile" :count="6"></Rboy-editor>
      <!-- <button @click="get_content">保存内容</button>
      <button @click="set_content">设置内容</button> -->
      <!-- 活动照片上传 -->
      <div style="display: flex; align-items: center">
        <div style="width: 90px">活动照片:</div>
        <div style="margin-top: 15px">
          <u-upload :fileList="fileList" @afterRead="afterRead" height="200" width="200" @delete="deletePic" name="3" :maxCount="10" :previewFullImage="true">
            <!-- 显示上传的图片 -->
            <div style="border: 1px #000000 dashed; border-radius: 3px; width: 200rpx; height: 200rpx; line-height: 200rpx; text-align: center">
              <image :src="images" style="width: 90px; height: 90px"></image>
            </div>
          </u-upload>
        </div>
      </div>
    </div>

    <!-- 详细信息模块 -->
    <div style="background-color: #fff; border-radius: 5px; padding: 10px; margin-top: 15px">
      <div style="display: flex; padding: 10px">
        <image src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
        <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">详细信息</div>
      </div>

      <!-- 活动时间选择器 -->
      <u-cell-group>
        <!-- <u-cell size="large" title="活动时间:" :value="typeValue1" @click="getType" isLink></u-cell> -->

        <u-cell size="large" title="活动开始时间:" :value="spForm.startTime" @click="getTypeStart" isLink></u-cell>
        <u-cell size="large" title="活动结束时间:" :value="spForm.endTime" @click="getTypeEnd" isLink :disabled="!spForm.startTime"></u-cell>
        <!-- 消费开关选择器 -->
        <u-cell size="large" title="是否上架活动:" :value="typeValue" @click="getTypelx" isLink></u-cell>

        <!-- 活动排序输入框 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">活动排序:</div>
          <input v-model="spForm.activeOrder" class="input_class" placeholder="请输入" />
        </div>
        <!-- 供应商收款 -->
        <div style="display: flex; align-items: center">
          <div style="width: 140px">供应商收款号:</div>
          <input v-model="spForm.subPayNoWater" class="input_class" placeholder="请输入" />
        </div>
        <!-- 供应商分账比例-->
        <div style="display: flex; align-items: center">
          <div style="width: 140px">供应商分账比例:</div>
          <input v-model="spForm.lsSplittingWater" class="input_class" placeholder="请输入" />
        </div>
        <!-- 商户分账比例 -->
        <div style="display: flex; align-items: center">
          <div style="width: 140px">商户分账比例:</div>
          <input v-model="spForm.lsSplittingCollection" class="input_class" placeholder="请输入" />
        </div>
        <!-- 平台分账比例 -->
        <div style="display: flex; align-items: center">
          <div style="width: 140px">平台分账比例:</div>
          <input v-model="spForm.lsSplittingPlatform" class="input_class" placeholder="请输入" />
        </div>
        <!-- 水站活动选择 -->
        <div style="display: flex; align-items: center">
          <div style="width: 140px">水卡活动:</div>
          <u-radio-group placement="row" v-model="spForm.isWatercard" @change="groupChange">
            <u-radio :size="30" :label-size="30" v-for="(item, index) in radiolist1" :key="index" :label="item.name" :name="item.label" @change="radioChange"> </u-radio>
          </u-radio-group>
        </div>
      </u-cell-group>

      <u-picker :show="showType" @cancel="showType = false" :columns="columns" keyName="categoryName" @confirm="getTsType"></u-picker>
    </div>
    <!--  <u-calendar :show="show" :mode="mode" rowHeight="100" @confirm="confirm"></u-calendar> -->
    <u-calendar
      :show="showStart"
      :mode="mode"
      rowHeight="150"
      @confirm="confirmStart"
      @close="showStart = false"
      :maxDate="calendar.maxDate"
      :monthNum="calendar.monthNum"
    ></u-calendar>
    <u-calendar :show="showEnd" :mode="mode" rowHeight="150" @confirm="confirmEnd" @close="showEnd = false" :maxDate="calendar.maxDate" :monthNum="calendar.monthNum"></u-calendar>

    <!-- 保存按钮 -->
    <u-button type="primary" v-if="spForm.isVendorActivity == 0" @click="addOwner">保存</u-button>
  </div>
</template>

<script>
import RboyEditor from '../../components/Rboy-editor/Rboy-editor.vue';
import { categorylist, addOrUpdateReId, merlist, activityById } from '../../utils/request_sh.js';
export default {
  components: {
    RboyEditor
  },

  data() {
    return {
      radiolist1: [
        {
          name: '是',
          label: 0
        },
        {
          name: '否',
          label: 1
        }
      ],
      calendar: {
        minDate: '',
        maxDate: '',
        defaultDate: '',
        monthNum: 36
      },
      showType: false, // 是否显示时间选择器
      columns: [], // 时间选择器数据源
      showEnd: false, // 是否显示日期选择器
      showStart: false, // 是否显示日期选择器
      mode: 'single', // 日期选择模式
      fileList: [], // 上传的文件列表
      typeValue1: '请选择活动周期', // 活动周期显示值
      typeValue: '请选择是否展示消费开关', // 消费开关显示值
      xiaoqumingc: '请选择小区', // 小区选择
      isType: '1', // 类型标识
      title: '',
      content: '',
      complaintCategory: '',
      complaintCategorys: '',
      estateId: '',
      fileName: '',
      images: '',
      stasus: '',
      // 活动表单数据
      spForm: {
        icon: '',
        name: '',
        illustrate: '',
        activeOrder: '',
        startTime: '',
        endTime: '',
        ebMerId: '',
        vouchers: [],
        activeOrder: '1',
        showInfo: '',
        stasus: '',
        isLaundry: 1,
        isWatercard: 1
      }
    };
  },
  onLoad(option) {
    this.getSpInfo(option.id);
    this.chooseTimed();
    // this.set_content();
  },
  methods: {
    // 设置内容
    async set_content() {
      this.$refs.RboyEditor.editor_setContents(this.spForm.showInfo);
    },
    // 获取内容
    async get_content() {
      this.spForm.showInfo = await this.$refs.RboyEditor.editor_getcontents();
      console.log('🚀 ~ get_content ~ this.spForm.showInfo:', this.spForm.showInfo);
    },
    // 上传图片
    async uploadFile(event) {
      // event 选择的图片
      for (var item in event.tempFilePaths) {
        // uploadFileApi  为上传到服务端的接口 count大于1 使用 await
        let src = await this.uploadFilePromise(event.tempFilePaths[item]);
        // src.url 是服务端返回的图片地址
        // this.$refs.RboyEditor(Object) 方法是往富文本设置图片内容  src 图片地址
        this.$refs.RboyEditor.editor_insertImage({
          src: 'https://www.wantongkonggu.cn/' + src.fileName,
          alt: '图像'
        });
      }
    },
    chooseTimed() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (month <= 9) {
        month = '0' + month;
      }
      if (day <= 9) {
        day = '0' + day;
      }
      let minyear = year - 2;
      let maxyear = year + 2;
      this.calendar.minDate = minyear + '-' + month + '-' + day;
      this.calendar.maxDate = maxyear + '-' + month + '-' + day;
      this.calendar.defaultDate = year + '-' + month + '-' + day;
    },
    // 确认选择的活动时间
    confirmStart(time) {
      this.spForm.startTime = time[0];
      this.showStart = false;
    },
    confirmEnd(time) {
      if (Date.parse(new Date(this.spForm.startTime)) > Date.parse(new Date(time[0]))) {
        uni.showToast({
          icon: 'none',
          title: '结束时间不能早于开始时间！'
        });
        this.showEnd = true;
        return;
      }
      this.spForm.endTime = time[0];
      this.showEnd = false;
    },
    getTypeStart() {
      this.showStart = true;
    },
    getTypeEnd() {
      this.showEnd = true;
    },
    // 确认选择的活动时间
    confirm(time) {
      this.typeValue1 = time[0] + '至' + time[time.length - 1];
      this.show = false;
    },
    // 获取商品信息
    getSpInfo(id) {
      activityById(id).then((res) => {
        this.spForm = res.data;
        this.typeValue = res.data.status == 0 ? '是' : '否';
        this.images = 'https://www.wantongkonggu.cn/' + res.data.icon;
        this.fileName = res.data.icon;
        this.spForm.startTime = res.data.startTime;
        this.spForm.endTime = res.data.endTime;
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.RboyEditor.editor_setContents(this.spForm.showInfo);
          }, 1000);
        });
      });
    },
    // 获取用户信息
    getUserInfo() {
      var userInfo = uni.getStorageSync('userInfo');
      var e = {
        merId: userInfo ? userInfo.merId : '',
        merName: ''
      };
      merlist(e).then((res) => {});
    },
    // 打开时间选择器
    getType() {
      this.show = true;
    },
    // 保存活动信息
    // 保存活动信息
    async addOwner() {
      await this.get_content();
      if (this.spForm.name == '' || this.fileName == '' || this.spForm.startTime == '' || this.spForm.endTime == '' || this.spForm.activeOrder == '') {
        uni.showToast({
          icon: 'none',
          title: '请填写完整信息！'
        });
        return;
      }

      // 验证分账比例之和必须等于1
      const waterSplit = parseFloat(this.spForm.lsSplittingWater) || 0;
      const collectionSplit = parseFloat(this.spForm.lsSplittingCollection) || 0;
      const platformSplit = parseFloat(this.spForm.lsSplittingPlatform) || 0;
      const totalSplit = waterSplit + collectionSplit + platformSplit;

      if (waterSplit && collectionSplit && platformSplit && totalSplit !== 1) {
        uni.showToast({
          icon: 'none',
          title: '供应商、商户、平台分账比例之和必须等于1！'
        });
        return;
      }

      var userInfo = uni.getStorageSync('userInfo');
      this.spForm.icon = this.fileName;
      this.spForm.startTime = this.spForm.startTime;
      this.spForm.endTime = this.spForm.endTime;
      this.spForm.ebMerId = userInfo.merId;
      this.spForm.activeOrder = this.spForm.activeOrder;
      this.spForm.stasus = this.stasus;
      addOrUpdateReId(this.spForm).then((res) => {
        // 新增元素成功后返回上一页并刷新数据
        if (res.code === 200) {
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          uni.$u.toast('操作成功');
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
              success: () => {
                prevPage.onLoad(); // 调用上一页的刷新方法
              }
            });
          }, 1000);
        } else {
          uni.showToast({
            icon: 'none',
            title: '系统错误，请联系管理员处理'
          });
        }
      });
    },
    // 确认选择的类型
    getTsType({ value }) {
      this.showType = false;
      this.typeValue = value[0].categoryName;
      this.stasus = value[0].merchantCategoryId;
    },
    // 打开消费开关选择器
    getTypelx() {
      this.showType = true;
      this.columns = [
        [
          { categoryName: '是', merchantCategoryId: '0' },
          { categoryName: '否', merchantCategoryId: '1' }
        ]
      ];
    },
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1);
    },
    // 上传文件
    async afterRead(event) {
      const result = await this.uploadFilePromise(event.file.url);
      this.images = 'https://www.wantongkonggu.cn/' + result.fileName;
      this.fileName = result.fileName;
    },
    // 上传文件请求
    uploadFilePromise(url) {
      const userInfo = uni.getStorageSync('userInfo');
      const token = userInfo ? userInfo.token : '';
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          header: {
            Authorization: token
          },
          url: 'https://www.wantongkonggu.cn//api/adminApph7/common/upload',
          filePath: url,
          name: 'file',
          formData: {
            user: 'test'
          },
          success: (res) => {
            resolve(JSON.parse(res.data));
          }
        });
      });
    }
  }
};
</script>

<style lang="scss">
/* 样式优化 */
.textarea_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}

.input_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}
</style>
